0535. TinyURL 的加密与解密【中等】
1. 📝 题目描述
TinyURL 是一种 URL 简化服务, 比如:当你输入一个 URL https://leetcode.com/problems/design-tinyurl 时,它将返回一个简化的 URL http://tinyurl.com/4e9iAk。请你设计一个类来加密与解密 TinyURL。
加密和解密算法如何设计和运作是没有限制的,你只需要保证一个 URL 可以被加密成一个 TinyURL,并且这个 TinyURL 可以用解密方法恢复成原本的 URL。
实现 Solution 类:
Solution()初始化 TinyURL 系统对象。String encode(String longUrl)返回longUrl对应的 TinyURL。String decode(String shortUrl)返回shortUrl原本的 URL。题目数据保证给定的shortUrl是由同一个系统对象加密的。
示例:
txt
输入:url = "https://leetcode.com/problems/design-tinyurl"
输出:"https://leetcode.com/problems/design-tinyurl"
解释:
Solution obj = new Solution();
string tiny = obj.encode(url); // 返回加密后得到的 TinyURL。
string ans = obj.decode(tiny); // 返回解密后得到的原本的 URL。1
2
3
4
5
6
7
2
3
4
5
6
7
提示:
1 <= url.length <= 10^4- 题目数据保证
url是一个有效的 URL
2. 🎯 s.1 - 自增 ID + 哈希表
c
#define MAX_URLS 100000
char* urls[MAX_URLS];
int urlCount = 0;
char* encode(char* longUrl) {
urls[urlCount] = longUrl;
char* shortUrl = (char*)malloc(64);
sprintf(shortUrl, "http://tinyurl.com/%d", urlCount);
urlCount++;
return shortUrl;
}
char* decode(char* shortUrl) {
int id;
sscanf(shortUrl, "http://tinyurl.com/%d", &id);
return urls[id];
}1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
js
const map = new Map()
let id = 0
/**
* @param {string} longUrl
* @return {string}
*/
var encode = function (longUrl) {
id++
const shortUrl = 'http://tinyurl.com/' + id
map.set(shortUrl, longUrl)
return shortUrl
}
/**
* @param {string} shortUrl
* @return {string}
*/
var decode = function (shortUrl) {
return map.get(shortUrl)
}1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
py
class Codec:
def __init__(self):
self.map = {}
self.id = 0
def encode(self, longUrl: str) -> str:
self.id += 1
shortUrl = f'http://tinyurl.com/{self.id}'
self.map[shortUrl] = longUrl
return shortUrl
def decode(self, shortUrl: str) -> str:
return self.map[shortUrl]1
2
3
4
5
6
7
8
9
10
11
12
13
2
3
4
5
6
7
8
9
10
11
12
13
- 时间复杂度:
encode和decode均为 - 空间复杂度:
, 为已编码 URL 数量
算法思路:
- 为每个 URL 分配自增 ID,作为短链接后缀
- 哈希表存储短链接到原始 URL 的映射